package com.afd.ozblip.activity;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import com.afd.ozblip.net.HttpUtil;
import com.afd.ozblip.util.AsyncAction;
import com.afd.ozblip.util.AsyncLoadData;
import com.afd.ozblip.util.Constants;
import com.afd.ozblip.util.ParseJson;
import com.afd.ozblip.util.StringUtil;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.util.Base64;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;

public class AddActivityActivity extends BaseActivity {

	/****************** 视图变量 **************************/
	private LinearLayout commonRight;
	private EditText activityTitleEt;
	private EditText activityDateEt;
	private EditText activityContentEt;
	private Button uploadBtn;
	private ImageView uploadImageIv;
	/****************** 数据变量 **************************/
	private String activityTitleStr;
	private String activityDateStr;
	private String activityContentStr;
	private boolean isChooseImage = false;
	private String fileBase64;
	private Bitmap headBitmap;
	private Map<String, Object> resultMap;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.add_activity);
		// 启动返回功能
		toBack();
		// 寻找视图
		findViews();
		// 设置监听
		setListeners();
		// 获取参数
		getBundle();
	}

	/**
	 * 寻找视图
	 */
	public void findViews() {
		this.commonRight = (LinearLayout) findViewById(R.id.ll_common_right);
		this.activityTitleEt = (EditText) findViewById(R.id.et_activity_title);
		this.activityDateEt = (EditText) findViewById(R.id.et_activity_date);
		this.activityContentEt = (EditText) findViewById(R.id.et_activity_content);
		this.uploadBtn = (Button) findViewById(R.id.btn_activity_upload);
		this.uploadImageIv = (ImageView) findViewById(R.id.iv_activity_image);
	}

	/**
	 * 设置监听
	 */
	public void setListeners() {
		View.OnClickListener addActivityClick = new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				switch (v.getId()) {
				case R.id.ll_common_right:
					activityTitleStr = activityTitleEt.getText().toString();
					activityDateStr = activityDateEt.getText().toString();
					activityContentStr = activityContentEt.getText().toString();
					if (verifyData()) {
						requestAddActivityData();
					}
					break;
				case R.id.et_activity_date:
					Calendar c = Calendar.getInstance();
					DatePickerDialog dialog = new DatePickerDialog(
							AddActivityActivity.this,
							new DatePickerDialog.OnDateSetListener() {
								public void onDateSet(DatePicker dp, int year,
										int month, int dayOfMonth) {
									int nowMonth = month + 1;
									activityDateEt.setText(year + "-"
											+ nowMonth + "-" + dayOfMonth);
								}
							}, c.get(Calendar.YEAR), // 传入年份
							c.get(Calendar.MONTH), // 传入月份
							c.get(Calendar.DAY_OF_MONTH) // 传入天数
					);
					dialog.show();
					break;
				case R.id.btn_activity_upload:
					showImageMenuDialog();
					break;
				default:
					break;
				}
			}
		};
		this.commonRight.setOnClickListener(addActivityClick);
		this.activityDateEt.setOnClickListener(addActivityClick);
		this.uploadBtn.setOnClickListener(addActivityClick);
	}

	/**
	 * 获取传递的参数
	 */
	private void getBundle() {
		// Intent intent = getIntent();
	}

	private byte[] mContent;

	private void showImageMenuDialog() {
		final String[] arrayFruit = new String[] { "相机拍摄", "手机相册" };

		final Dialog alertDialog = new AlertDialog.Builder(
				AddActivityActivity.this).setTitle("图片来源")
				.setIcon(android.R.drawable.ic_dialog_info)
				.setItems(arrayFruit, new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// switch (which) {
						// case 0:
						// Intent cameraI = new Intent(
						// MediaStore.ACTION_IMAGE_CAPTURE);
						// cameraI.putExtra(MediaStore.EXTRA_OUTPUT, Uri
						// .fromFile(new File(Environment
						// .getExternalStorageDirectory(),
						// "temp.jpg")));
						// startActivityForResult(cameraI, PHOTOHRAPH);
						// break;
						// case 1:
						// Intent pictureI = new Intent(Intent.ACTION_PICK,
						// null);
						// pictureI.setDataAndType(
						// MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
						// IMAGE_UNSPECIFIED);
						// startActivityForResult(pictureI, PHOTOZOOM);
						// break;
						//
						// default:
						// break;
						// }
						if (which == 0) {
							Intent getImageByCamera = new Intent(
									"android.media.action.IMAGE_CAPTURE");
							startActivityForResult(getImageByCamera, 1);
						} else {
							Intent getImage = new Intent(
									Intent.ACTION_GET_CONTENT);
							getImage.addCategory(Intent.CATEGORY_OPENABLE);
							getImage.setType("image/jpeg");
							startActivityForResult(getImage, 0);
						}
					}
				}).create();
		alertDialog.show();
	}

	protected void onActivityResult(int requestCode, int resultCode,
			Intent intent) {
		switch (requestCode) {
		case 0:
			try {
				ContentResolver resolver = getContentResolver();
				// 获得图片的uri
				Uri originalUri = intent.getData();
				// 将图片内容解析成字节数组
				mContent = readStream(resolver.openInputStream(Uri
						.parse(originalUri.toString())));
				if (mContent == null) {
					return;
				}
				// 将字节数组转换为ImageView可调用的Bitmap对象
				headBitmap = getPicFromBytes(mContent, null);
				uploadImageIv.setImageBitmap(headBitmap);
				fileBase64 = Base64.encodeToString(mContent, Base64.DEFAULT);
				isChooseImage = true;
			} catch (Exception e) {
				// System.out.println(e.getMessage());
			}
			break;
		case 1:
			try {
				super.onActivityResult(requestCode, resultCode, intent);
				if (intent == null) {
					return;
				}
				Bundle extras = intent.getExtras();
				headBitmap = (Bitmap) extras.get("data");
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				headBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
				mContent = baos.toByteArray();
				fileBase64 = Base64.encodeToString(mContent, Base64.DEFAULT);
				uploadImageIv.setImageBitmap(headBitmap);
				isChooseImage = true;
			} catch (Exception e) {
				e.printStackTrace();
			}

			break;

		default:
			break;
		}
	}

	public static Bitmap getPicFromBytes(byte[] bytes,
			BitmapFactory.Options opts) {
		if (bytes != null)
			if (opts != null)
				return BitmapFactory.decodeByteArray(bytes, 0, bytes.length,
						opts);
			else
				return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
		return null;
	}

	public static byte[] readStream(InputStream inStream) throws Exception {
		byte[] buffer = new byte[1024];
		int len = -1;
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		while ((len = inStream.read(buffer)) != -1) {
			outStream.write(buffer, 0, len);
		}
		byte[] data = outStream.toByteArray();
		outStream.close();
		inStream.close();
		return data;

	}

	/**
	 * 验证数据
	 */
	private boolean verifyData() {
		if (StringUtil.isNullOrEmpty(activityTitleStr)) {
			showLongToast(this, "请输入活动标题", true);
			return false;
		}
		if (StringUtil.isNullOrEmpty(activityDateStr)) {
			showLongToast(this, "请输入活动标题", true);
			return false;
		}
		if (StringUtil.isNullOrEmpty(activityContentStr)) {
			showLongToast(this, "请输入活动标题", true);
			return false;
		}
		if (!isChooseImage) {
			showLongToast(this, "请选择图片！", true);
			return false;
		}
		return true;
	}

	// TODO 获取发布活动数据
	/**
	 * 获取发布活动数据
	 */
	private void requestAddActivityData() {
		AsyncLoadData ald = new AsyncLoadData(this, "加载中...", false,
				new AsyncAction() {

					@Override
					public void doLoad() throws Exception {
						// 获取提交参数
						Map<String, Object> addDishParamMap = new HashMap<String, Object>();
						addDishParamMap.put("activityTitle", activityTitleStr);
						addDishParamMap.put("activityDate", activityDateStr);
						addDishParamMap.put("activityContent",
								activityContentStr);
						addDishParamMap.put("uploadImg", fileBase64);
						// 发送请求
						byte[] bRecommend = HttpUtil.requestByPost(
								AddActivityActivity.this,
								Constants.ADD_ACTIVITY_API, addDishParamMap);
						if (bRecommend != null) {
							resultMap = new ParseJson()
									.parseAddResultJson(bRecommend);
						}
					}

					@Override
					public void loadEnd() throws Exception {
						boolean returnFlg = (Boolean) resultMap
								.get("returnFlg");
						if (returnFlg) {
							showShortToast(AddActivityActivity.this, resultMap
									.get("regMessage").toString(), true);
							finish();
						} else {
							System.out.println(resultMap.get("regMessage")
									.toString());
							showShortToast(AddActivityActivity.this, "发布失败",
									true);
						}
					}

				});
		ald.execute(0);

	}
}